<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select" clearable>
        <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
      </el-input>
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-table :data="users"  stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作">
          <template v-slot="scope">
          <!-- 编辑用户 -->
            <el-button 
              type="primary" 
              icon="el-icon-edit" 
              size="mini"
              @click="editUser(scope.row.id)"></el-button>
            <!-- 删除用户 -->
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              size="mini"
              @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false"> 
              <el-button type="warning" icon="el-icon-s-tools" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>      
      <el-pagination     
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>     
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addClose">
      <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px">
        <el-form-item  label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的正则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 正确的邮箱
        return callback()
      } else {
        return callback(new Error('请输入正确的邮箱'))
      }
    }
    // 验证手机号的正则
    var checkmobile = (rule, value, callback) => {
      const regmobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regmobile.test(value)) {
        // 正确的手机
        return callback()
      } else {
        return callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      pagenum: '',
      users: [],
      switchBtn:true,
      editDialogVisible:false,      
      addDialogVisible:false,
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      editForm:{},

      addRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur',},
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editRules:{
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {params: this.queryInfo,})
      //console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.pagenum = res.data.pagenum
      this.total = res.data.total
      this.users = res.data.users
    },
    // 切换下拉菜单时触发
    handleSizeChange(value){
      this.queryInfo.pagesize = value
      this.getUsersList()
    },
    // 页码变化时触发
    handleCurrentChange(value){
      this.queryInfo.pagenum = value
      this.getUsersList()
    },
    async changeState(userInfo){
      const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      console.log(res)
      if(res.meta.status !==200){
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更改用户状态失败')
      }    
      this.$message.success('更改用户状态成功')
    },
    // 添加用户
    addUser(){
      this.addDialogVisible = true
    },
    addClose(){
      this.$refs.addForm.resetFields()
    },
    addDialogUser(){
      this.$refs.addForm.validate( async value => {
        if(!value) return 
        const {data:res} = await this.$http.post('users',this.addForm)
        console.log(res)
        if(res.meta.status !== 201){
          return this.$message.error('添加用户失败')
        } 
        this.addDialogVisible = false
        this.$message.success('添加用户成功')
        this.getUsersList()
      })
      
    },
    // 编辑用户
    async editUser(id){
      this.editDialogVisible = true
      const {data:res} = await this.$http.get('users/' + id)
      //console.log(res)
      if(res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editForm = res.data
    },
    editClose(){
      this.$refs.editForm.resetFields()
    },
    editDialogUser(){
       this.$refs.editForm.validate( async value => {
        if(!value) return 
        const {data:res} = await this.$http.put('users/' + this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        //console.log(res)
        if(res.meta.status !== 200) return this.$message.error('修改用户失败')
        this.$message.success('修改用户成功')
        this.editForm = res.data
        this.getUsersList()
        this.editDialogVisible = false
       })
    }, 
    // 删除用户
    async deleteUser(id){
      const result = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        console.log(result);
        if(result !== 'confirm') return this.$message.error('取消删除')
        const {data:res} = await this.$http.delete('users/' + id)
          //console.log(res)
          if(res.meta.status !== 200) return this.$message.error('删除用户失败')
          this.getUsersList()
    }  
  }
}
</script>

<style lang="less" scoped>
div /deep/ .el-card {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-top: 20px;

  .el-input {
    width: 35%;
    margin-right: 20px;
  }

  .el-table{
    margin: 20px 0;
  }
}
</style>